#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
作者: jena 
时间: 2025.9
数据处理工具包 - 离线环境优化版本
这个包提供了字符清洗、句子筛选、API服务等功能。
专为内网环境设计，所有依赖已预打包，无需外网连接。

核心模块:
- CharacterCleaner: 字符级文本清洗
- SentenceCleaner: 句子级文本筛选  
- API服务器: RESTful接口
- 配置管理: 统一参数配置
"""

# 离线包路径设置 - 使用统一函数
from .common_utils import setup_offline_packages_path
setup_offline_packages_path(__file__)

# 包信息
__version__ = "1.0.0"
__author__ = "jena"
__description__ = "数据处理工具包 - 离线环境优化版本"

# 依赖检查和导入管理
import sys
import warnings
from typing import Optional, Dict, Any

def _check_dependencies() -> Dict[str, bool]:
    """检查离线包依赖是否正确安装 - 只使用offline_packages目录"""
    deps_status = {}

    from .common_utils import safe_import

    # 仅检查 FastAPI & Uvicorn（ASGI 模式）
    fastapi_module, _ = safe_import('fastapi', 'fastapi', 'FastAPI不可用')
    deps_status['fastapi'] = fastapi_module is not None
    uvicorn_module, _ = safe_import('uvicorn', 'uvicorn', 'Uvicorn不可用')
    deps_status['uvicorn'] = uvicorn_module is not None
    if not deps_status['fastapi']:
        warnings.warn("FastAPI未从offline_packages安装，ASGI模式不可用")
    if not deps_status['uvicorn']:
        warnings.warn("Uvicorn未从offline_packages安装，ASGI模式不可用")

    # 其他
    requests_module, _ = safe_import('requests', 'requests', 'HTTP客户端不可用')
    deps_status['requests'] = requests_module is not None
    if not deps_status['requests']:
        warnings.warn("Requests未从offline_packages安装，部分功能可能受限")

    bs4_module, _ = safe_import('bs4', 'beautifulsoup4', 'HTML解析不可用')
    deps_status['beautifulsoup4'] = bs4_module is not None
    if not deps_status['beautifulsoup4']:
        warnings.warn("BeautifulSoup4未从offline_packages安装，HTML清理功能将使用回退方案")

    jieba_module, _ = safe_import('jieba', 'jieba', '中文分词不可用')
    deps_status['jieba'] = jieba_module is not None
    if not deps_status['jieba']:
        warnings.warn("jieba未从offline_packages安装，中文分词功能不可用")

    opencc_module, _ = safe_import('opencc', 'opencc-python-reimplemented', '繁简转换不可用')
    deps_status['opencc'] = opencc_module is not None
    if not deps_status['opencc']:
        warnings.warn("OpenCC未从offline_packages安装，繁简转换功能不可用")

    return deps_status

# 执行依赖检查
_DEPS_STATUS = _check_dependencies()

# 核心模块导入 - 使用绝对导入避免循环依赖
try:
    from .config import CharacterCleanerConfig, SentenceCleanerConfig
    from .common_utils import safe_import, TeeOutput, LogManager
    from .character_cleaner import CharacterCleaner
    from .sentence_cleaner import SentenceCleaner
    
    # API服务器导入 - 仅FastAPI
    app = None
    _API_AVAILABLE = False
    if _DEPS_STATUS.get('fastapi', False):
        try:
            from .api_server_fastapi import app as _app
            app = _app
            _API_AVAILABLE = True
        except Exception as e:
            warnings.warn(f"FastAPI应用导入失败: {e}")
        
except ImportError as e:
    raise ImportError(f"核心模块导入失败: {e}. 请检查离线包是否正确安装。")

# 公共接口
__all__ = [
    # 核心类
    'CharacterCleaner',
    'SentenceCleaner',
    
    # 配置类
    'CharacterCleanerConfig', 
    'SentenceCleanerConfig',
    
    # 工具函数
    'safe_import',
    'TeeOutput',
    'LogManager',
    
    # API服务器 (如果可用)
    'app',
    
    # 状态查询
    'get_dependencies_status',
    'is_api_available',
    'get_package_info'
]

def get_dependencies_status() -> Dict[str, bool]:
    """获取依赖包安装状态"""
    return _DEPS_STATUS.copy()

def is_api_available() -> bool:
    """检查API服务器是否可用"""
    return _API_AVAILABLE

def get_package_info() -> Dict[str, Any]:
    """获取包信息"""
    return {
        'name': 'data_process_toolkit',
        'version': __version__,
        'author': __author__,
        'description': __description__,
        'dependencies_status': get_dependencies_status(),
        'api_available': is_api_available(),
        'python_version': sys.version,
        'offline_mode': True
    }